define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/material/index' + location.search,
                    add_url: 'scanwork/material/add',
                    edit_url: 'scanwork/material/edit',
                    del_url: 'scanwork/material/del',
                    multi_url: 'scanwork/material/multi',
                    import_url: 'scanwork/material/import',
                    table: 'scanwork_material',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                escape: true, // 全局转义，但特定列可以覆盖
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: '物料名称', operate: 'LIKE'},
                        {field: 'code', title: '物料编码', operate: 'LIKE'},
                        {field: 'category.name', title: '物料分类', formatter: function(value, row, index) {
                            return value || '未分类';
                        }},
                        {field: 'spec', title: '规格型号', operate: 'LIKE'},
                        {field: 'unit', title: '单位', formatter: Table.api.formatter.normal},
                        {field: 'current_price', title: '参考价', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value).toFixed(4);
                        }},
                        {field: 'stock', title: '库存', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return value + ' ' + row.unit;
                        }},
                        {field: 'stock_status', title: '库存状态', escape: false, formatter: function(value, row, index) {
                            var stock = parseFloat(row.stock) || 0;
                            var minStock = parseFloat(row.min_stock) || 0;
                            var safetyStock = parseFloat(row.safety_stock) || 0;
                            
                            if (stock <= 0) {
                                return '<span class="label label-danger">缺货</span>';
                            } else if (stock < minStock) {
                                return '<span class="label label-warning">库存不足</span>';
                            } else if (stock < safetyStock) {
                                return '<span class="label label-info">低于安全库存</span>';
                            } else {
                                return '<span class="label label-success">正常</span>';
                            }
                        }},
                        {field: 'default_supplier.name', title: '默认供应商', operate: 'LIKE'},
                        {field: 'status', title: __('Status'), operate: 'in', formatter: Table.api.formatter.status},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 绑定采购申请按钮事件
            $(document).on('click', '.btn-purchase-request', function() {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Toastr.warning('请选择要生成采购申请的物料');
                    return;
                }
                
                // 检查选中的物料是否缺货
                var shortageIds = [];
                table.bootstrapTable('getData').forEach(function(row) {
                    if (ids.indexOf(row.id) !== -1 && (row.stock <= 0 || row.stock < row.min_stock)) {
                        shortageIds.push(row.id);
                    }
                });
                
                if (shortageIds.length === 0) {
                    Toastr.warning('选中的物料库存充足，无需采购');
                    return;
                }
                
                Fast.api.open('scanwork/purchase_request/shortage', '缺货物料列表', {
                    callback: function(data) {
                        table.bootstrapTable('refresh');
                    }
                });
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                
                // 供应商报价管理
                var supplierIndex = $('.supplier-item').length;
                
                // 添加供应商
                $('#add-supplier').click(function() {
                    var html = '<div class="supplier-item" data-index="' + supplierIndex + '">' +
                        '<div class="row">' +
                        '<div class="col-md-3">' +
                        '<select name="suppliers[' + supplierIndex + '][supplier_id]" class="form-control" required>' +
                        '<option value="">选择供应商</option>' +
                        $('#c-default_supplier_id option').each(function() {
                            if ($(this).val()) {
                                html += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
                            }
                        }) +
                        '</select>' +
                        '</div>' +
                        '<div class="col-md-2">' +
                        '<input type="number" name="suppliers[' + supplierIndex + '][price]" class="form-control" placeholder="报价" step="0.0001" required>' +
                        '</div>' +
                        '<div class="col-md-2">' +
                        '<input type="number" name="suppliers[' + supplierIndex + '][min_order_qty]" class="form-control" placeholder="起订量" step="0.01" value="1">' +
                        '</div>' +
                        '<div class="col-md-2">' +
                        '<input type="number" name="suppliers[' + supplierIndex + '][delivery_days]" class="form-control" placeholder="交货期" value="7">' +
                        '</div>' +
                        '<div class="col-md-2">' +
                        '<label class="checkbox-inline">' +
                        '<input type="checkbox" name="suppliers[' + supplierIndex + '][is_preferred]" value="1"> 优先' +
                        '</label>' +
                        '</div>' +
                        '<div class="col-md-1">' +
                        '<button type="button" class="btn btn-danger btn-sm remove-supplier">删除</button>' +
                        '</div>' +
                        '</div>' +
                        '</div>';
                    
                    $('#supplier-list').append(html);
                    supplierIndex++;
                });
                
                // 删除供应商
                $(document).on('click', '.remove-supplier', function() {
                    $(this).closest('.supplier-item').remove();
                });
            }
        }
    };
    return Controller;
});
